<template>
  <el-dialog
    v-model="visible"
    title="文件上传"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <div class="upload-content">
      <div 
        v-for="(file, index) in fileList" 
        :key="index" 
        class="upload-item"
      >
        <div class="upload-info">
          <span class="file-name">{{ file.file.name }}</span>
          <span class="file-size">{{ formatFileSize(file.file.size) }}</span>
        </div>
        <div class="upload-progress">
          <el-progress 
            :percentage="file.progress" 
            :status="getStatus(file.status)"
          />
        </div>
        <div class="upload-actions">
          <el-button 
            v-if="file.status === 'error'" 
            type="primary" 
            size="small"
            @click="retryUpload(index)"
          >
            重试
          </el-button>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="startUpload" 
          :loading="uploading"
          :disabled="uploadButtonDisabled"
        >
          {{ uploading ? '上传中...' : '开始上传' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { formatFileSize, uploadFile } from '@/utils'

// 定义组件属性
const props = defineProps<{
  modelValue: boolean
}>()

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'upload-success'): void
}>()

// 文件列表
const fileList = ref<Array<{
  file: File
  progress: number
  status: 'waiting' | 'uploading' | 'success' | 'error'
}>>([])

// 上传状态
const uploading = ref(false)

// 可见性计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 计算上传按钮是否禁用
const uploadButtonDisabled = computed(() => {
  // 上传中禁用
  if (uploading.value) return true
  
  // 没有文件时禁用
  if (fileList.value.length === 0) return true
  
  // 所有文件都上传成功时禁用
  const allSuccess = fileList.value.every(file => file.status === 'success')
  return allSuccess
})

// 监听可见性变化
watch(visible, (newVal) => {
  if (!newVal) {
    // 关闭时重置状态
    setTimeout(() => {
      fileList.value = []
      uploading.value = false
    }, 300)
  }
})

// 设置文件列表
const setFiles = (files: FileList) => {
  fileList.value = Array.from(files).map(file => ({
    file,
    progress: 0,
    status: 'waiting'
  }))
}

// 获取状态映射
const getStatus = (status: string) => {
  switch (status) {
    case 'success':
      return 'success'
    case 'error':
      return 'exception'
    default:
      return undefined
  }
}

// 重试上传
const retryUpload = (index: number) => {
  const fileItem = fileList.value[index]
  fileItem.status = 'waiting'
  fileItem.progress = 0
}

// 开始上传
const startUpload = async () => {
  if (uploading.value) return
  
  uploading.value = true
  let successCount = 0
  let errorCount = 0
  
  try {
    // 逐个上传文件
    for (let i = 0; i < fileList.value.length; i++) {
      const uploadItem = fileList.value[i]
      
      // 跳过已经成功的文件
      if (uploadItem.status === 'success') {
        successCount++
        continue
      }
      
      uploadItem.status = 'uploading'
      
      try {
        const response = await uploadFile(uploadItem.file, {
          onProgress: (progress) => {
            uploadItem.progress = progress
          }
        })
        
        if (response.code === 200) {
          uploadItem.status = 'success'
          successCount++
        } else {
          uploadItem.status = 'error'
          uploadItem.progress = 0
          errorCount++
        }
      } catch (error) {
        uploadItem.status = 'error'
        uploadItem.progress = 0
        errorCount++
      }
    }
    
    // 显示汇总消息
    if (successCount > 0) {
      ElMessage.success(`成功上传 ${successCount} 个文件`)
    }
    
    if (errorCount > 0) {
      ElMessage.error(`${errorCount} 个文件上传失败`)
    } else {
      // 上传完成，触发成功事件但不自动关闭弹窗
      emit('upload-success')
    }
  } finally {
    uploading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  if (uploading.value) {
    ElMessage.warning('文件上传中，请稍后关闭')
    return
  }
  visible.value = false
}

// 暴露方法给父组件
defineExpose({
  setFiles
})
</script>

<style scoped>
.upload-content {
  max-height: 400px;
  overflow-y: auto;
}

.upload-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 12px;
}

.upload-item:last-child {
  margin-bottom: 0;
}

.upload-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.file-name {
  color: #606266;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
}

.file-size {
  color: #909399;
  white-space: nowrap;
}

.upload-progress {
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>